package com.lz.ccjdemo.http.interceptor;


import android.content.Context;
import android.content.pm.PackageInfo;

import com.lz.ccjdemo.App;
import com.lz.ccjdemo.http.HttpConfig;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**********************************************************************
 * @desc http 头部拦截器
 * @author lz
 * @data 2020/9/21 or 11:19
 *====================================================================*/
public class HeadInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        //拦截retrofit注解的header配置信息
        Request addParamRequest = addHeader(chain.request(), chain);
        return chain.proceed(addParamRequest);
    }

    /**
     * 添加请求头
     *
     * @param oldRequest
     * @return
     */
    public Request addHeader(Request oldRequest, Chain chain) {
        String appVersion = "";
        try {
            PackageInfo info = App.getApp().getPackageManager()
                    .getPackageInfo(App.getApp().getPackageName(), 0);
            appVersion = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Request.Builder builder = oldRequest.newBuilder();
        builder.addHeader("token", HttpConfig.getConfig().getToken())
                .addHeader("customerType", "android")
                .addHeader("appVersion", appVersion);
        HashMap<String,String> headers=HttpConfig.getConfig().getHeaders();
        if (headers!=null&&headers.size()>0){
            // 遍历HashMap
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                builder.addHeader(key,value);
            }
        }
        return builder.build();
    }

}
